﻿using System;
using System.Linq;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using IFDB.Models.Contexts;
using IFDB.ResourceLibrary;
using IFDB.Models.Foundation;

namespace IFDB.Models.Tables
{
    public class Person : BaseTable<Person>
    {
        public Person()
        {
            this.AppearanceEvents = new HashSet<AppearanceEvent>();
            this.LookupPersons = new HashSet<LookupPerson>();
        }

        [Key]
        public Guid PersonId { get; set; }

        [StringLength(50)]
        public string Surname { get; set; }

        [StringLength(50)]
        public string Forenames { get; set; }

        public Nullable<DateTime> DOB { get; set; }
        public Position Position { get; set; }

        public virtual ICollection<AppearanceEvent> AppearanceEvents { get; set; }
        public virtual ICollection<LookupPerson> LookupPersons { get; set; }

        public static Person CreateNew(string surname, string forenames, DateTime? dob, Position position)
        {
            return new Person()
            {
                PersonId = Guid.NewGuid(),
                Surname = surname,
                Forenames = forenames,
                DOB = dob,
                Position = position
            };
        }

        public static Person Update(Person person, string surname, string forenames, DateTime? dob, Position position)
        {
            person.Surname = surname;
            person.Forenames = forenames;
            person.DOB = dob;
            person.Position = position;

            return person;
        }

        public static Person Search(IFDBContext db, Guid personId)
        {
            var localQuery = from person in db.Persons.Local
                             where person.PersonId == personId
                             select person;

            var query = from person in db.Persons
                        where person.PersonId == personId
                        select person;

            var search = ProcessSearch(localQuery, query, false);
            return search != null ? search.Single() : null;
        }
    }
}
